<template>
  <div class="favorite-list">
    <div class="header">
      <h2>我的收藏与喜欢</h2>
    </div>
    
    <el-tabs v-model="activeTab" class="main-tabs">
      <el-tab-pane label="我的收藏" name="collection">
        <div class="sub-header">
          <div class="total">共 {{ collectionTotal }} 条收藏</div>
        </div>
        
        <div class="list-container">
          <el-table 
            :data="collectionList" 
            style="width: 100%"
            v-loading="loading"
            @row-click="handleRowClick"
          >
            <el-table-column prop="title" label="标题" width="300">
              <template #default="{ row }">
                <div class="title-cell">
                  <router-link :to="'/news/' + row.id" @click.stop>
                    <el-image
                      :src="row.picPath || '/src/assets/images/wZhi.jpeg'"
                      fit="cover"
                      class="cover-image"
                    ></el-image>
                  </router-link>
                  <router-link :to="'/news/' + row.id" class="title-text" @click.stop>
                    {{ row.title }}
                  </router-link>
                </div>
              </template>
            </el-table-column>
            <!-- 分类 -->
            <el-table-column prop="categoryName" label="分类" width="180">
              <template #default="{ row }">
                <router-link :to="'/news/' + row.id" @click.stop>
                  <el-tag :type="getTagType(row.categoryId)">
                    {{ row.categoryName }}
                  </el-tag>
                </router-link>
              </template>
            </el-table-column>
            <el-table-column prop="userName" label="作者" width="180">
              <template #default="{ row }">
                <router-link :to="'/news/' + row.id" @click.stop>
                  {{ row.userName }}
                </router-link>
              </template>
            </el-table-column>
            <el-table-column prop="userName" label="作者" width="180" />

            <!-- <el-table-column prop="createDate" label="收藏时间" width="180" /> -->
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click.stop="handleUncollect(row.favoriteId)"
                  :loading="uncollectLoading[row.favoriteId]"
                >
                  取消收藏
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            v-model:current-page="collectionPage"
            v-model:page-size="pageSize"
            :total="collectionTotal"
            layout="total, prev, pager, next, jumper"
            @current-change="fetchCollectionData"
          />
        </div>
      </el-tab-pane>

      <el-tab-pane label="我的喜欢" name="like">
        <div class="sub-header">
          <div class="total">共 {{ likeTotal }} 条喜欢</div>
        </div>
        
        <div class="list-container">
          <el-table 
            :data="likeList" 
            style="width: 100%"
            v-loading="loading"
            @row-click="handleRowClick"
          >
            <el-table-column prop="title" label="标题" width="300">
              <template #default="{ row }">
                <div class="title-cell">
                  <router-link :to="'/news/' + row.id" @click.stop>
                    <el-image
                      :src="row.picPath || bgimg"
                      fit="cover"
                      class="cover-image"
                    ></el-image>
                  </router-link>
                  <router-link :to="'/news/' + row.id" class="title-text" @click.stop>
                    {{ row.title }}
                  </router-link>
                </div>
              </template>
            </el-table-column>
            
            <!-- 添加分类列 -->
            <el-table-column prop="categoryName" label="分类" width="180">
              <template #default="{ row }">
                <router-link :to="'/news/' + row.id" @click.stop>
                  <el-tag :type="getTagType(row.categoryId)">
                    {{ row.categoryName }}
                  </el-tag>
                </router-link>
              </template>
            </el-table-column>
            
            <el-table-column prop="userName" label="作者" width="180">
              <template #default="{ row }">
                <router-link :to="'/news/' + row.id" @click.stop>
                  {{ row.userName }}
                </router-link>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click.stop="handleUnlike(row.likeId)"
                  :loading="unlikeLoading[row.likeId]"
                >
                  取消喜欢
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            v-model:current-page="likePage"
            v-model:page-size="pageSize"
            :total="likeTotal"
            layout="total, prev, pager, next, jumper"
            @current-change="fetchLikeData"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'
import bgimg from '@/assets/images/wZhi.jpeg'

const router=useRouter()



const props = defineProps({
   id: {  // 改为接收id
    type: Number,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  }
})

// 添加行点击事件处理.跳转页面
const handleRowClick = (row) => {
  router.push('/news/' + row.id)
}

const activeTab = ref('collection')
const pageSize = ref(5)

// 收藏相关数据
const collectionPage = ref(1)
const collectionTotal = ref(0)
const collectionList = ref([])
const uncollectLoading = ref({})

// 喜欢相关数据
const likePage = ref(1)
const likeTotal = ref(0)
const likeList = ref([])
const unlikeLoading = ref({})
// 分类映射表
const categoryMap = ref({
  '1': '热点新闻',
  '2': '研发·编程',
  '3': '虚拟·现实',
  '4': '产品·运营',
  '5': '视觉·创意',
  '6': '职场·考试',
  '7': '体育新闻',
  '8': '财经新闻'
})

// 标签类型映射
const tagTypeMap = {
  '1': 'danger',    // 热点新闻 - 红色
  '2': 'success',   // 研发·编程 - 绿色
  '3': 'warning',   // 虚拟·现实 - 黄色
  '4': 'primary',   // 产品·运营 - 蓝色
  '5': 'info',      // 视觉·创意 - 青色
  '6': '',          // 职场·考试 - 默认
  '7': 'danger',    // 体育新闻 - 红色
  '8': 'warning'    // 财经新闻 - 黄色
}

const getTagType = (categoryId) => {
  return tagTypeMap[categoryId] || ''
}

// 收藏数据获取
const fetchCollectionData = async () => {
  try {
    const response = await axios.get('/api/news/getNewsByFavorite', {
      params: {
        user_id: props.id
      }
    })
    
    if (response.data.code === 200) {
      // 添加分类名称到每条数据
      collectionList.value = response.data.data.map(item => ({
        ...item,
        categoryName: categoryMap.value[item.categoryId] || '未知分类'
      }))
      
      collectionTotal.value = collectionList.value.length
      
      // 分页处理
      collectionList.value = collectionList.value.slice(
        (collectionPage.value - 1) * pageSize.value,
        collectionPage.value * pageSize.value
      )
    }
  } catch (error) {
    ElMessage.error('获取收藏列表失败')
    console.error('Error fetching collection data:', error)
  }
}


// 喜欢
// 修改后的喜欢数据获取方法
const fetchLikeData = async () => {
  try {
    const response = await axios.get('/api/news/getNewsByLike', {
      params: {
        user_id: props.id
      }
    })
    
    if (response.data.code === 200) {
      // 添加分类名称到每条数据
      likeList.value = response.data.data.map(item => ({
        ...item,
        categoryName: categoryMap.value[item.categoryId] || '未知分类'
      }))
      
      likeTotal.value = likeList.value.length
      
      // 分页处理
      likeList.value = likeList.value.slice(
        (likePage.value - 1) * pageSize.value,
        likePage.value * pageSize.value
      )
    }
  } catch (error) {
    ElMessage.error('获取喜欢列表失败')
    console.error('Error fetching like data:', error)
  }
}

//handleUncollect

const handleUncollect = async (favoriteId) => {
  try {
    uncollectLoading.value[favoriteId] = true;
    await ElMessageBox.confirm('确定要取消收藏吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await axios.post(`/api/favorites/delectFavorites/${favoriteId}`);
    
    if (response.data?.code === 200) {
      ElMessage.success(response.data.message || '取消收藏成功');
      await fetchCollectionData(); // 重新加载数据
    } else {
      ElMessage.error(response.data?.message || '取消收藏失败');
    }
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data?.message || '服务器错误');
    } else if (error !== 'cancel') {
      ElMessage.error(error.message);
    }
  } finally {
    uncollectLoading.value[favoriteId] = false;
  }
}

const handleUnlike = async (likeId) => {
  try {
    unlikeLoading.value[likeId] = true
    await ElMessageBox.confirm('确定要取消喜欢吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 使用正确的模板字符串语法
    const response = await axios.post(`/api/like/delectLike/${likeId}`)
    
    if (response.data && response.data.code === 200) {
      ElMessage.success('取消喜欢成功')
      // 重新获取最新数据
      await fetchLikeData()
    } else {
      ElMessage.error(response.data?.message || '取消喜欢失败')
    }
  } catch (error) {
    if (error.response) {
      // 有HTTP响应但状态码不是2xx
      ElMessage.error(error.response.data?.message || '服务器错误')
    } else if (error !== 'cancel') {
      ElMessage.error('请求失败: ' + error.message)
    }
  } finally {
    unlikeLoading.value[likeId] = false
  }
}

onMounted(() => {
  fetchCollectionData()
  fetchLikeData()
})
</script>

<style scoped>
.favorite-list {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.main-tabs {
  margin-top: 10px;
}

.sub-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.total {
  color: #909399;
  font-size: 14px;
}

.list-container {
  margin-top: 20px;
}

.title-cell {
  display: flex;
  align-items: center;
}

.cover-image {
  width: 80px;
  height: 60px;
  margin-right: 10px;
  border-radius: 4px;
  cursor: pointer;
}

.title-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #333;
  text-decoration: none;
  cursor: pointer;
}

.title-text:hover {
  color: #409eff;
  text-decoration: underline;
}

/* 添加可点击行的样式 */
:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 确保操作按钮区域不会触发行点击 */
:deep(.el-table__cell:last-child) {
  cursor: default !important;
}

:deep(.el-table__cell:last-child:hover) {
  background-color: transparent !important;
}
</style>